package org.example.project3.Controller;

import lombok.extern.slf4j.Slf4j;
import org.example.project3.Constant.JwtConstant;
import org.example.project3.Context.BaseContext;
import org.example.project3.DTO.RegisterDTO;
import org.example.project3.DTO.UserupdateDTO;
import org.example.project3.Entity.User;
import org.example.project3.Result_.Result;
import org.example.project3.Service.UserServiceImpl;
import org.example.project3.Utils.JwtUtils;
import org.example.project3.VO.UserLoginVO;
import org.example.project3.VO.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/bigevent/user")
@Slf4j
public class UserController{
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private JwtConstant JWTCONSTANT;
    /**
     * 注册新用户(用户名和密码)
     * @param dto
     * @return
     */
    @PostMapping("/add")
    public Result add(@RequestBody RegisterDTO dto){
        Integer user_id = userService.add(dto);
        return Result.success(user_id);
    }
    @PostMapping("/login")
    public Result login(@RequestBody RegisterDTO dto) throws Exception{
        //如果用户名和密码正确，生成令牌返回，否则抛出异常
        User user= userService.login(dto);
        Map<String, Object> claims = new HashMap<>();
        claims.put(JWTCONSTANT.getUser_id(), user.getId());
        String token = JwtUtils.createJWT(
                JWTCONSTANT.getSecretKey(),
                JWTCONSTANT.getExpired_time(),
                claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .token(token)
                .build();

        return Result.success(userLoginVO);
    }

    /**
     * 查用户信息
     * @return
     */
    @GetMapping
    public Result getUserstatistics(){
        UserVO vo = userService.getUserstatistics();
        return Result.success(vo);
    }

    /**
     * 更新用户资料
     * @param dto
     * @return
     */
    @PutMapping("/update")
    public Result update(@RequestBody UserupdateDTO dto){
        userService.update(dto);
        return Result.success();
    }

    /**
     * 修改头像
     * @param image
     * @return
     */
    @PutMapping("/update/image")
    public Result update_image(String image){
        UserupdateDTO dto = new UserupdateDTO();
        dto.setImage(image);
        userService.update(dto);
        return Result.success();

    }

    @PutMapping("/update/password")
    public Result update_password(String password){
        UserupdateDTO dto = new UserupdateDTO();
        dto.setPassword(password);
        userService.update(dto);
        return Result.success();
    }
}
